import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
import { getMeterReportApi, getMetersReportApi } from '@/api/meter'
import { ElMessage } from 'element-plus'

export const useWaterBalanceStore = defineStore('waterBalance', () => {
    // 状态定义
    const nodes = ref([]) // 存储原始节点数据
    const totalVi = ref(0) // 总取水量
    const loading = ref(false) // 加载状态
    const mergedNodes = ref([]) // 保存合并区域的配置

    // 计算可用于合并的区域
    const availableAreas = computed(() => {
        const mergedAreaSet = new Set(
            mergedNodes.value.flatMap(config => config.selectedAreas)
        )
        return nodes.value.filter(node => !mergedAreaSet.has(node.label))
    })

    // 获取未合并的独立节点
    const independentNodes = computed(() => {
        const mergedAreaLabels = new Set(
            mergedNodes.value.flatMap(config => config.selectedAreas)
        )
        return nodes.value.filter(node => !mergedAreaLabels.has(node.label))
    })

    // 计算总的漏水量
    const leakageVi = computed(() => {
        const nodesViSum = processedNodes.value.reduce((sum, node) => {
            return sum + Number(node.vi || 0)
        }, 0)
        return Number((totalVi.value - nodesViSum).toFixed(2))
    })

    // 验证合并区域配置
    const validateMergeConfig = (config) => {
        if (!config.name?.trim()) {
            throw new Error('合并区域名称不能为空')
        }
        // 只需要选择至少一个区域
        if (!Array.isArray(config.selectedAreas) || config.selectedAreas.length < 1) {
            throw new Error('请至少选择一个区域进行合并')
        }
        // 验证耗水比例和排水比例之和是否为10
        if (Math.abs((config.consumptionRatio + config.drainageRatio) - 10) > 0.1) {
            throw new Error('耗水比例与排水比例之和必须等于10')
        }

        // 检查选择的区域是否已被其他配置使用
        const otherConfigs = mergedNodes.value.filter(item => item.id !== config.id)
        const usedAreas = new Set(otherConfigs.flatMap(item => item.selectedAreas))
        const conflictAreas = config.selectedAreas.filter(area => usedAreas.has(area))

        if (conflictAreas.length > 0) {
            throw new Error(`以下区域已被其他配置使用: ${conflictAreas.join(', ')}`)
        }

        return true
    }

    // 计算合并区域的水量
    const calculateMergedAreaData = (config) => {
        // 获取所有符合选中区域名称的节点
        const areasToMerge = nodes.value.filter(node =>
            config.selectedAreas.includes(node.label)
        )

        // 计算总取水量
        const totalVi = areasToMerge.reduce((sum, area) => sum + Number(area.vi || 0), 0)
        const ratioSum = config.consumptionRatio + config.drainageRatio

        // 计算耗水量和排水量
        const vco = Number((totalVi * (config.consumptionRatio / ratioSum)).toFixed(2))
        const vd = Number((totalVi * (config.drainageRatio / ratioSum)).toFixed(2))

        return {
            label: config.name,
            vi: Number(totalVi.toFixed(2)),
            vco,
            vd,
            consumptionRatio: config.consumptionRatio,
            drainageRatio: config.drainageRatio,
            mergedAreas: config.selectedAreas,
            originalNodes: areasToMerge.map(area => ({
                label: area.label,
                vi: area.vi
            }))
        }
    }

    // 处理所有节点数据
    const processedNodes = computed(() => {
        // 处理合并区域
        const processedMergedNodes = mergedNodes.value.map(config =>
            calculateMergedAreaData(config)
        )

        // 处理独立节点
        const processedIndependentNodes = independentNodes.value.map(node => {
            const total = Number(node.vi || 0)
            const ratioSum = node.consumptionRatio + node.drainageRatio
            const vco = Number((total * (node.consumptionRatio / ratioSum)).toFixed(2))
            const vd = Number((total * (node.drainageRatio / ratioSum)).toFixed(2))

            return {
                ...node,
                vi: Number(total.toFixed(2)),
                vco,
                vd
            }
        })

        return [...processedMergedNodes, ...processedIndependentNodes]
    })

    // 添加新的合并区域
    const addMergeConfig = (config) => {
        try {
            const newConfig = {
                ...config,
                id: Date.now()
            }
            validateMergeConfig(newConfig)
            mergedNodes.value.push(newConfig)
            return true
        } catch (error) {
            ElMessage.error(error.message)
            return false
        }
    }

    // 更新合并区域配置
    const updateMergeConfig = (config) => {
        try {
            validateMergeConfig(config)
            const index = mergedNodes.value.findIndex(item => item.id === config.id)
            if (index !== -1) {
                mergedNodes.value[index] = config
            } else {
                throw new Error('未找到要更新的合并区域配置')
            }
            return true
        } catch (error) {
            ElMessage.error(error.message)
            return false
        }
    }

    // 删除合并区域
    const removeMergeConfig = (configId) => {
        const index = mergedNodes.value.findIndex(item => item.id === configId)
        if (index !== -1) {
            mergedNodes.value.splice(index, 1)
            return true
        }
        ElMessage.warning('未找到要删除的合并区域配置')
        return false
    }

    // 获取一级表数据
    async function fetchFirstLevelData(meters) {
        try {
            loading.value = true
            let res = await getMetersReportApi({
                meters: meters,
                start_time: dayjs().subtract(8, 'day').startOf('day').valueOf(),
                end_time: dayjs().subtract(1, 'day').endOf('day').valueOf(),
                interval: 'day'
            })

            const validData = res.aggregated_data.filter(item => item.Value !== null && item.Value !== undefined)
            totalVi.value = validData.length > 0
                ? Number((validData.reduce((acc, cur) => acc + (+cur.Value), 0) / validData.length).toFixed(2))
                : 0
        } catch (error) {
            console.error('获取一级表数据失败:', error)
            ElMessage.error('获取一级表数据失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取二级表数据
    async function fetchSecondLevelData(meters, areaStore) {
        try {
            loading.value = true
            const nodePromises = meters.map(async (meter) => {
                let res = await getMeterReportApi({
                    id: meter.id,
                    start_time: dayjs().subtract(8, 'day').startOf('day').valueOf(),
                    end_time: dayjs().subtract(1, 'day').endOf('day').valueOf(),
                    interval: 'day'
                })

                const validData = res.aggregated_data.filter(item => item.Value !== null && item.Value !== undefined)
                const Vi = validData.length > 0
                    ? Number((validData.reduce((acc, cur) => acc + (+cur.Value), 0) / validData.length).toFixed(2))
                    : 0

                return {
                    label: areaStore.getAreaNameById(meter.area_id),
                    vi: Vi,
                    consumptionRatio: 9,
                    drainageRatio: 1
                }
            })

            nodes.value = await Promise.all(nodePromises)
            // 重置合并区域配置
            mergedNodes.value = []
        } catch (error) {
            console.error('获取节点数据失败:', error)
            ElMessage.error('获取节点数据失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 重置所有数据
    const resetAll = () => {
        nodes.value = []
        totalVi.value = 0
        mergedNodes.value = []
        loading.value = false
    }

    return {
        // 状态
        nodes,
        totalVi,
        loading,
        leakageVi,
        processedNodes,
        mergedNodes,
        availableAreas,
        independentNodes,

        // 方法
        fetchFirstLevelData,
        fetchSecondLevelData,
        addMergeConfig,
        updateMergeConfig,
        removeMergeConfig,
        validateMergeConfig,
        calculateMergedAreaData,
        resetAll
    }
})